<template>
  <div class="userEidt">
    <p class="titleadd">{{ operation ? "用户新增" : "用户编辑" }}</p>
    <div class="eidtform">
      <el-form
        :model="dataForm"
        label-width="100px"
        :rules="dataFormRules"
        ref="dataForm"
        class="addForm"
      >
        <el-form-item label="ID" prop="id" v-if="false">
          <el-input
            v-model="dataForm.id"
            :disabled="true"
            auto-complete="off"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input
            v-model="dataForm.name"
            auto-complete="off"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="登录名 " prop="username">
          <el-input
            v-model="dataForm.username"
            v-if="operation"
            auto-complete="off"
            clearable
          ></el-input>
          <el-input
            v-model="dataForm.username"
            v-if="!operation"
            :disabled="true"
            auto-complete="off"
          ></el-input>
        </el-form-item>

        <el-form-item v-if="operation" label="密码 " prop="password">
          <el-input
            v-model="dataForm.password"
            auto-complete="off"
            clearable
          ></el-input>
        </el-form-item>

        <el-form-item label="电话 " prop="phone">
          <el-input
            v-model="dataForm.phone"
            auto-complete="off"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="描述 " prop="des">
          <el-input
            v-model="dataForm.des"
            auto-complete="off"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="后台标题">
          <el-input
            v-model="dataForm.houtai_title"
            auto-complete="off"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="邮箱 " prop="mail">
          <el-input
            v-model="dataForm.mail"
            auto-complete="off"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="角色关联" prop="userTypeId">
          <el-cascader
            v-model="dataForm.userTypeId"
            :options="userProps"
            :show-all-levels="false"
            @change="changeDefaultId"
          ></el-cascader>
        </el-form-item>

        <el-form-item label="所属机构 " prop="mail" v-if="!operation">
          <el-input v-model="dataForm.groupName" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div class="subbtn">
        <el-button @click.native="cancelbut">取消</el-button>
        <el-button type="primary" @click.native="submitForm">确定</el-button>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  props: {
    Gid: {
      type: String,
      default: "",
    },
    operation: {
      type: Boolean,
      default: true,
    },
    dataForm: {
      type: Object,
      default: () => {
        return {};
      },
    },
    options: {
      type: Array,
      default: () => {
        return [];
      },
    },
    pageResult: {
      type: Array,
      default: () => {
        return [];
      },
    },
  },
  data() {
    let that = this;
    return {
      defaultRoleList: [],
      roleList: [],
      userProps: [
        {
          value: 1,
          label: `角色配置`,
          children: [],
        },
        {
          value: 2,
          label: `默认角色`,
          children: [],
        },
      ],
      dataFormRules: {
        userTypeId: [
          {
            message: "角色关联不能为空",
            required: true,
            trigger: "blur",
          },
        ],
        name: [
          {
            required: true,
            message: "名称不能为空",
            trigger: "blur",
          },
        ],
        password: [
          {
            message: "密码不能为空",
            trigger: "blur",
            required: true,
          },
        ],
        username: [
          {
            required: true,
            message: "用户名不能为空",
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    //默认角色
    getUserList() {
      // 这是个函数 所以传参进去
      this.$api.role
        .defaultRole_list()
        .then((res) => {
          if (res.code == 0) {
            this.defaultRoleList = res.data;
            let params = {
              where: { GID: this.Gid },
            };
            this.$api.role.findPage(params).then((res) => {
              if (res.code == 0) {
                this.loading = false;

                this.roleList = res.data;
                this.setUserProps();
              } else {
                this.$message({
                  message: "网络异常,请重试 " + res.msg,
                  type: "error",
                });
              }
            });
          }
        })
        .catch((err) => {
          // 这里是如果接口报错 或者网络不好。接口请求失败的结果 一般来说需要做处理 比如弹出警告窗提醒用户
          this.$message({
            message: "网络异常,请重试 ",
            type: "error",
          });
        });
    },
    // 拼接图片
    getItemPhoto(id) {
      var url = this.global.baseUrlImage + "avatar/" + id;
      return url;
    },
    //图片处理
    getBase64(file) {
      return new Promise(function (resolve, reject) {
        let reader = new FileReader();
        let imgResult = "";
        reader.readAsDataURL(file);
        reader.onload = function () {
          imgResult = reader.result;
        };
        reader.onerror = function (error) {
          reject(error);
        };
        reader.onloadend = function () {
          resolve(imgResult);
        };
      });
    },
    // 图片上传
    async handleUpLoad(param, fileList) {
      var imgup = "";
      await this.getBase64(param.file).then((res) => {
        imgup = res;
      });
      var paramd = {
        img: imgup,
      };
      var snn = JSON.stringify(paramd);
      this.$api.imgAdd
        .addimgPer(snn)
        .then((res) => {
          if (res.code == 0) {
            this.dataForm.imgs.push(res.id);
          } else {
            this.$message({
              message: res.msg,
              type: "info",
            });
          }
        })
        .catch((err) => {
          this.$message({
            message: err,
            type: "info",
          });
        });
    },
    // 网格图片上传
    async handleUpLoad1(param, fileList) {
      var imgup = "";
      await this.getBase64(param.file).then((res) => {
        imgup = res;
      });
      var paramd = {
        img: imgup,
      };
      var snn = JSON.stringify(paramd);
      this.$api.imgAdd
        .addimgPer(snn)
        .then((res) => {
          if (res.code == 0) {
            this.dataForm.photo.push(res.id);
          } else {
            this.$message({
              message: res.msg,
              type: "info",
            });
          }
        })
        .catch((err) => {
          this.$message({
            message: err,
            type: "info",
          });
        });
    },
    beforeAvatarUpload(file) {
      // var testmsg = file.name.substring(file.name.lastIndexOf(".") + 1);
      // const extension = testmsg === "jpg";
      // const extension2 = testmsg === "png";
      const isLt2M = file.size / 1024 / 1024 < 10;
      // if (!extension && !extension2) {
      //   this.$message({
      //     message: "上传文件只能是 jpg、png格式!",
      //     type: "warning"
      //   });
      // }
      if (!isLt2M) {
        this.$message({
          message: "上传文件大小不能超过 10MB!",
          type: "warning",
        });
      }
      // return extension || (extension2 && isLt2M);
      return isLt2M;
      // console.log("dd", file);
    },
    beforeAvatarUpload1(file) {
      const isLt2M = file.size / 1024 / 1024 < 10;
      if (!isLt2M) {
        this.$message({
          message: "上传文件大小不能超过 10MB!",
          type: "warning",
        });
      }
      return isLt2M;
    },
    //   删除图片
    deleteImg(item, index) {
      this.$confirm("确认删除此照片吗？", "提示", {}).then(() => {
        this.dataForm.imgs.splice(index, 1);
      });
    },
    //   删除网格图片
    deleteImg1(item, index) {
      this.$confirm("确认删除此照片吗？", "提示", {}).then(() => {
        this.dataForm.photo.splice(index, 1);
      });
    },
    // 保存调用的方法
    submitForm: function () {
      this.$refs.dataForm.validate((valid) => {
        if (valid) {
          this.$confirm("确认提交吗？", "提示", {}).then(() => {
            this.editLoading = true;
            let obj = JSON.parse(JSON.stringify(this.dataForm));
            // 处理默认角色参数
            if (obj.userTypeId[0] === 1) {
              obj.role_id = obj.userTypeId[1];
              delete obj.defaultId;
            } else {
              obj.defaultId = obj.userTypeId[1];
              delete obj.role_id;
            }
            delete obj.userTypeId;
            // if (obj && obj.defaultId && Array.isArray(obj.defaultId)) {
            //   obj.defaultId = obj.defaultId[1];
            // } else {
            //   delete obj.defaultId;
            // }
            if (obj.password) {
              obj.password = this.$md5(obj.password);
            }

            let params = {
              rows: obj,
              where: {
                _id: obj._id,
              },
            };
            let paramJson = JSON.stringify(params);
            this.$api.user.save(paramJson).then((res) => {
              this.editLoading = false;
              if (res.code == 0) {
                this.$message({
                  message: "操作成功",
                  type: "success",
                });
                this.dialogVisible = false;
                this.$refs["dataForm"].resetFields();
                this.$refs.uploadImg.clearFiles();
                this.$emit("getMsg");
              } else {
                this.$message({
                  message: "操作失败, " + res.msg,
                  type: "error",
                });
              }
            });
          });
        }
      });
    },
    //   取消
    cancelbut() {
      this.$emit("getMsg");
    },
    setUserProps() {
      let arr = [];

      for (let i = 0; i < this.roleList.length; i++) {
        const val = this.roleList[i];
        arr.push({
          value: val._id,
          label: val.name,
          leaf: true,
        });
      }
      this.userProps[0].children = arr;
      arr = [];
      for (let i = 0; i < this.defaultRoleList.length; i++) {
        const val = this.defaultRoleList[i];
        arr.push({
          value: val._id,
          label: val.name,
          leaf: true,
        });
      }
      this.userProps[1].children = arr;

      let old = JSON.parse(JSON.stringify(this.dataForm));
      // 回显
      if (old.defaultId) {
        this.dataForm.userTypeId = old.defaultId;
      } else if (old.role_id) {
        this.dataForm.userTypeId = old.role_id;
      }
    },
    changeDefaultId(val) {
      console.log(val);
    },
  },

  mounted() {
    this.getUserList();
  },
};
</script>

<style lang="scss" scoped>
.userEidt {
  height: 100%;
  overflow: hidden;
}
.titleadd {
  top: 0;
  line-height: 50px;
  padding: 0 20px;
  border-left: 5px solid rgb(30, 175, 243);
  margin-bottom: 20px;
}
.eidtform {
  margin: 0 auto;
  height: 90%;
  overflow-y: auto;
  .subbtn {
    margin: 20px auto;
    width: 200px;
  }
}
.addForm {
  padding-left: 40px;
  box-sizing: border-box;
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  justify-content: start;
  .el-form-item {
    width: 45%;
    margin-bottom: 40px;
  }

  /* .el-form-item{
      width: 45%;
  } */
}
</style>
